from winpkg import *
if __name__=="__main__":

  CMDS = ("install", "upgrade", "remove", "list", "update")
  USAGE = "cmd %%prog (%s) [args]"%'|'.join(CMDS)

  import optparse
  parser = optparse.OptionParser()
  parser.set_usage(USAGE)
  parser.add_option("-D", "--debug", action="store_true", dest="debug")
  parser.add_option("-v", "--version", action="store_true", dest="version")
  parser.add_option("-f", "--force", action="store_true", dest="force")
  parser.add_option("-d", "--download-only", action="store_true", dest="download_only")
  parser.add_option("-r", "--repositories", dest="repositories")
  parser.add_option("","--remove-standalone", action="store_true", dest="windows_uninstall", help=optparse.SUPPRESS_HELP)

  parser.set_defaults(repositories=DEFAULT_REPOSITORIES)

  import sys
  cmd = len(sys.argv)>1 and sys.argv[1]

  if cmd=="list":
    parser.add_option("-i", "--installed", action="store_true", dest="installed")
    parser.add_option("-u", "--upgraded", action="store_true", dest="upgraded")

  (options, args) = parser.parse_args()

  logging.basicConfig(level = options.debug and logging.DEBUG or logging.INFO)
  if options.version:
    from version import VERSION, DATE
    logging.info('version: %s, %s',VERSION, DATE)
    sys.exit(0)
  repo = Repo(repositories = options.repositories.split(','))
  if options.windows_uninstall:
    for name in args:
      meta = repo.get(name)
      if meta.is_installed():
        meta.remove_standalone()
      else:
        logging.warning('%s is not installed',name)
    sys.exit(0)

  if cmd=="install" or cmd=="remove":
    for name in args[1:]:
      meta = repo.get(name)
      if not meta:
        print name, "not found, skipping"
        continue
      if cmd=="install":
        if options.force or not meta.is_installed() or meta.is_newer():
          meta.install(download_only = options.download_only)
        else:
          print name, "is already installed"
      elif cmd=="remove":
        if not meta.is_installed():
          print name, "is not installed, skipping"
          continue
        meta.uninstall()
  elif cmd=="upgrade":
    if args[1:]:
      for name in args[1:]:
        item = repo.get(name)
        if not item:
          logging.warning("%s not found, skipping",name)
          continue
        if item.is_newer() or options.force:
          item.install(download_only = options.download_only)
        else:
          logging.warning("newer version installed, skipping")
    else:
      for item in repo.to_upgrade():
        item.install(download_only = options.download_only)
  elif cmd=="list":
    if options.installed:
      items = repo.installed()
    elif options.upgraded:
      items = repo.to_upgrade()
    else:
      items = repo.all()
    cnt = 0
    for p in items:
      print p.name, options.installed and p.installed_version or p.version or ''
      cnt+=1
    if not cnt:
      logging.info('empty package list - try update')
  elif cmd=="update":
    import simplejson as json
    from urllib2 import urlopen,Request
    from urllib import urlencode
    repos = options.repositories.split(',')
    
    def update():
      for repo_name in repos:
        logging.info('updating %s',repo_name)
        last = not options.force and repo.last_modified(repo_name) or ''
        logging.info("last modified: %s",last)
        req = Request((REPO_URL%repo_name)+'?'+urlencode({'from':last}),headers={'Accept':'application/json'})
        packages = json.loads(urlopen(req).read())
        if packages:
          for p in packages:
            repo.update(p)
          repo.commit()
        else:
          logging.info('%s repository is up to date',repo_name)
    
    if options.force:
      repo.empty()
    try:
      update()
    except sqlite3.OperationalError, e:
      if not options.force:
        logging.warning("db schema change? reloading...")
        repo.empty()
        update()
      else:
        raise e
    
  else:
    logging.info('invalid command')
    import sys
    parser.print_help()
    sys.exit(1)

